package org.alys114.springcloud.pbook.service;

import org.alys114.springcloud.pbook.client.MemberClient;
import org.alys114.springcloud.pbook.client.MemberDTO;
import org.alys114.springcloud.pbook.client.MemberRestResult;
import org.alys114.springcloud.pbook.entity.Book;
import org.alys114.springcloud.pbook.entity.Borrow;
import org.alys114.springcloud.pbook.repository.BookRepository;
import org.alys114.springcloud.pbook.repository.BorrowRepository;
import org.alys114.springcloud.pbook.service.exception.BookNotFoundException;
import org.alys114.springcloud.pbook.service.exception.MemberNotFoundException;
import org.alys114.springcloud.pbook.service.exception.NotEnoughStockException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author: Vincent.chan
 * @date: 2019/9/24 10:29
 * @version: v1.0
 * @Description: TODO<描述>
 */

@Service
public class BookService {
    @Resource
    private BookRepository bookRepository;

    public List<Book> findAll(){
        return bookRepository.findAll();
    }

    public Book getBookByBid(Integer bid){
        Optional<Book> optionalBook = bookRepository.findById(bid);
        Book book = null;
        if(optionalBook.isPresent()){
            book = optionalBook.get();
        }else {
            throw new BookNotFoundException("图书[" + bid + "] 没找到......");
        }
        return book;
    }

    @Resource
    private MemberClient memberClient;
    @Resource
    private BorrowRepository borrowRepository;

    @Transactional
    public void borrow(Integer bid, String mobile, Date takedate,Date returndate)
    {
        // 1. 获取book信息
        Book book = this.getBookByBid(bid);
        // 2. 检查库存
        if(book.getStock()<1){
            throw new NotEnoughStockException("库存不足...");
        }
        // 3. 获取Member信息
        MemberRestResult memberRestResult = memberClient.checkMobile(mobile);
        MemberDTO memberDTO = null;
        if(memberRestResult.getCode().equals("0")){
            memberDTO = memberRestResult.getData();
        }else{
            throw new MemberNotFoundException("手机[" + mobile + "]获取不到用户信息...");
        }
        // 4. 核心逻辑
        // 4.1 写入借阅表
        Borrow borrow = new Borrow();
        borrow.setBid(bid);
        borrow.setMid(memberDTO.getMid());
        borrow.setTakedate(takedate);
        borrow.setReturndate(returndate);
        borrow.setCreatetime(new Date());
        borrowRepository.saveAndFlush(borrow);


        // 4.2 更新库存
        book.setStock(book.getStock()-1);
        bookRepository.saveAndFlush(book);
    }
}
